<template>
  <div class="pending-bills-container">
    <div class="page-header">
      <el-button @click="goHome" circle size="large" class="back-btn">
        <el-icon><ArrowLeft /></el-icon>
      </el-button>
      <h1>📋 待审批账单</h1>
      <el-badge :value="pendingCount" :hidden="pendingCount === 0" type="danger">
        <el-icon :size="24"><Bell /></el-icon>
      </el-badge>
    </div>

    <div v-loading="loading" class="pending-list">
      <!-- 空状态 -->
      <div v-if="bills.length === 0" class="empty-state">
        <el-empty description="暂无待审批账单">
          <template #image>
            <div class="empty-icon">✅</div>
          </template>
          <p class="empty-tip">太棒了！所有账单都已处理完毕</p>
        </el-empty>
      </div>

      <!-- 账单列表 -->
      <div v-else class="bill-cards">
        <div v-for="bill in bills" :key="bill.id" class="bill-card">
          <!-- 卡片头部 -->
          <div class="card-header">
            <div class="header-left">
              <span class="category-icon">{{ getCategoryIcon(bill.category) }}</span>
              <div class="header-info">
                <div class="bill-purpose">{{ bill.purpose }}</div>
                <div class="bill-meta">
                  <span class="bill-category">{{ bill.category }}</span>
                  <span class="bill-date">{{ formatDateTime(bill.createdAt) }}</span>
                </div>
              </div>
            </div>
            <div class="bill-amount">¥{{ formatAmount(bill.amount) }}</div>
          </div>

          <!-- 账单详情 -->
          <div class="card-body">
            <div class="detail-item">
              <span class="label">📅 账单日期：</span>
              <span class="value">{{ formatDate(bill.billDate) }}</span>
            </div>
            
            <!-- 截图预览 -->
            <div v-if="bill.images && bill.images.length > 0" class="images-preview">
              <div class="label">📷 截图：</div>
              <div class="images-grid">
                <el-image
                  v-for="(img, index) in bill.images"
                  :key="index"
                  :src="getImageUrl(img)"
                  :preview-src-list="bill.images.map(i => getImageUrl(i))"
                  :initial-index="index"
                  fit="cover"
                  class="preview-image" />
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="card-footer">
            <el-button 
              type="success" 
              size="large" 
              @click="approveBillAction(bill.id, true)"
              :loading="processingBillId === bill.id"
              round>
              <el-icon><Select /></el-icon>
              <span>同意</span>
            </el-button>
            <el-button 
              type="danger" 
              size="large" 
              @click="showRejectDialog(bill.id)"
              :loading="processingBillId === bill.id"
              round>
              <el-icon><CloseBold /></el-icon>
              <span>拒绝</span>
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 拒绝理由对话框 -->
    <el-dialog v-model="showRejectDialogVisible" title="❌ 拒绝理由" width="90%" :close-on-click-modal="false">
      <el-form :model="rejectForm" :rules="rejectRules" ref="rejectFormRef" label-width="0">
        <el-form-item prop="rejectReason">
          <el-input
            v-model="rejectForm.rejectReason"
            type="textarea"
            :rows="5"
            placeholder="请详细说明拒绝理由，如：金额过高、用途不合理等"
            maxlength="200"
            show-word-limit />
        </el-form-item>
        <el-alert 
          title="温馨提示：拒绝后对方会收到通知，请友好沟通哦 💕" 
          type="warning" 
          :closable="false" 
          show-icon />
      </el-form>
      <template #footer>
        <el-button @click="showRejectDialogVisible = false" size="large">取消</el-button>
        <el-button 
          type="danger" 
          @click="submitReject" 
          :loading="submitting"
          size="large">
          确定拒绝
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Bell, Select, CloseBold, ArrowLeft } from '@element-plus/icons-vue'
import { getPendingBills, approveBill } from '@/api'

const router = useRouter()

// 分类图标映射
const categoryIcons = {
  '餐饮': '🍔',
  '购物': '🛍️',
  '交通': '🚗',
  '娱乐': '🎮',
  '医疗': '💊',
  '教育': '📚',
  '住房': '🏠',
  '其他': '📦'
}

// 响应式数据
const bills = ref([])
const loading = ref(false)
const submitting = ref(false)
const processingBillId = ref(null)
const showRejectDialogVisible = ref(false)
const currentBillId = ref(null)

// 表单数据
const rejectForm = ref({ rejectReason: '' })
const rejectFormRef = ref(null)

// 表单验证规则
const rejectRules = {
  rejectReason: [
    { required: true, message: '请填写拒绝理由', trigger: 'blur' },
    { min: 5, max: 200, message: '长度在 5 到 200 个字符', trigger: 'blur' }
  ]
}

// 待审批数量
const pendingCount = computed(() => bills.value.length)

// 获取分类图标
const getCategoryIcon = (category) => {
  return categoryIcons[category] || '📦'
}

// 格式化金额
const formatAmount = (amount) => {
  if (amount === null || amount === undefined) return '0.00'
  return Number(amount).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' })
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  const now = new Date()
  const diff = now - date
  const minutes = Math.floor(diff / 60000)
  const hours = Math.floor(diff / 3600000)
  const days = Math.floor(diff / 86400000)

  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`
  
  return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' })
}

// 获取图片URL
const getImageUrl = (url) => {
  if (!url) return ''
  if (url.startsWith('http')) return url
  return import.meta.env.VITE_API_BASE_URL + url
}

// 加载待审批账单
const loadPendingBills = async () => {
  loading.value = true
  try {
    const res = await getPendingBills()
    if (res.code === 200) {
      bills.value = res.data.map(bill => ({
        ...bill,
        images: bill.images ? JSON.parse(bill.images) : []
      }))
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.msg || '加载失败')
  } finally {
    loading.value = false
  }
}

// 显示拒绝对话框
const showRejectDialog = (billId) => {
  currentBillId.value = billId
  rejectForm.value.rejectReason = ''
  showRejectDialogVisible.value = true
}

// 审批账单
const approveBillAction = async (billId, approved) => {
  try {
    await ElMessageBox.confirm(
      `确定同意这笔 ${bills.value.find(b => b.id === billId)?.amount} 元的账单吗？`,
      '确认同意',
      {
        confirmButtonText: '确定同意',
        cancelButtonText: '再想想',
        type: 'success',
        confirmButtonClass: 'confirm-approve-btn'
      }
    )

    processingBillId.value = billId
    const res = await approveBill({
      billId,
      approved,
      rejectReason: null
    })

    if (res.code === 200) {
      ElMessage.success('✅ 已同意账单')
      // 从列表中移除已处理的账单
      bills.value = bills.value.filter(b => b.id !== billId)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.msg || '操作失败')
    }
  } finally {
    processingBillId.value = null
  }
}

// 提交拒绝
const submitReject = async () => {
  await rejectFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const res = await approveBill({
          billId: currentBillId.value,
          approved: false,
          rejectReason: rejectForm.value.rejectReason
        })

        if (res.code === 200) {
          ElMessage.success('❌ 已拒绝账单')
          showRejectDialogVisible.value = false
          // 从列表中移除已处理的账单
          bills.value = bills.value.filter(b => b.id !== currentBillId.value)
        }
      } catch (error) {
        ElMessage.error(error.response?.data?.msg || '操作失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 返回主页
const goHome = () => {
  router.push('/home')
}

// 页面加载时获取数据
onMounted(() => {
  loadPendingBills()
})
</script>

<style scoped>
.pending-bills-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #ffeef8 0%, #fff5f7 100%);
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 24px;
  font-weight: bold;
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.back-btn {
  background: white;
  border: none;
  box-shadow: 0 2px 12px rgba(255, 154, 158, 0.2);
}

.pending-list {
  min-height: 400px;
}

.empty-state {
  background: white;
  border-radius: 24px;
  padding: 60px 20px;
  text-align: center;
  box-shadow: 0 4px 20px rgba(255, 154, 158, 0.15);
}

.empty-icon {
  font-size: 80px;
  margin-bottom: 20px;
}

.empty-tip {
  font-size: 14px;
  color: #999;
  margin-top: 10px;
}

.bill-cards {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.bill-card {
  background: white;
  border-radius: 24px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(255, 154, 158, 0.15);
  transition: all 0.3s ease;
  border-left: 4px solid #ff9a9e;
}

.bill-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 30px rgba(255, 154, 158, 0.25);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.header-left {
  display: flex;
  gap: 12px;
  flex: 1;
}

.category-icon {
  font-size: 40px;
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #ffeef8 0%, #fff5f7 100%);
  border-radius: 16px;
}

.header-info {
  flex: 1;
}

.bill-purpose {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.bill-meta {
  display: flex;
  gap: 12px;
  font-size: 13px;
  color: #999;
}

.bill-amount {
  font-size: 28px;
  font-weight: bold;
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.card-body {
  margin-bottom: 20px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-size: 14px;
}

.detail-item .label {
  color: #666;
}

.detail-item .value {
  color: #333;
  font-weight: 500;
}

.images-preview {
  margin-top: 16px;
}

.images-preview .label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  display: block;
}

.images-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 8px;
}

.preview-image {
  width: 100%;
  height: 80px;
  border-radius: 8px;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.preview-image:hover {
  transform: scale(1.05);
}

.card-footer {
  display: flex;
  gap: 12px;
}

.card-footer .el-button {
  flex: 1;
  height: 50px;
  font-size: 16px;
  font-weight: bold;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .pending-bills-container {
    padding: 15px;
  }

  .page-header h1 {
    font-size: 20px;
  }

  .card-header {
    flex-direction: column;
    gap: 12px;
  }

  .bill-amount {
    font-size: 24px;
  }

  .images-grid {
    grid-template-columns: repeat(3, 1fr);
  }

  .card-footer {
    flex-direction: column;
  }

  .card-footer .el-button {
    width: 100%;
  }
}
</style>

